package logic

import (
	"context"
	"math"
	"reflect"

	"googee/common/uniqueid"
	"googee/common/utils"
	"googee/service/account/model"
	"googee/service/account/rpc/internal/svc"
	"googee/service/account/rpc/types/account"

	"github.com/fatih/color"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type TransOutTryLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTransOutTryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TransOutTryLogic {
	return &TransOutTryLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 转出尝试
func (l *TransOutTryLogic) TransOutTry(in *account.TransOutRequest) (*account.Empty, error) {

	//检查用户的账号里面余额是否足够
	configValue := reflect.ValueOf(l.svcCtx.Config.Digital)
	precision := configValue.FieldByName(utils.FirstUpper(in.GetField())).Uint()

	t := int64(math.Pow10(int(precision)))

	err := l.svcCtx.SqlConn.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		err := l.svcCtx.AccountModel.AdjustTrading(ctx, in.Id, in.Field, -in.Amount, uint8(precision))
		if err != nil {
			return err
		}

		_, err = l.svcCtx.AccountLogModel.Insert(ctx, &model.AccountLog{
			Id:      uniqueid.GenId(),
			Dir:     TRANOUT,
			Name:    in.Field,
			TransId: in.TransId,
			Amount:  t * in.Amount,
			UserId:  in.Id,
			Typ:     in.Typ,
			Subtyp:  in.Subtyp,
			Comment: in.Comment,
		})

		return err
	})

	if err != nil {
		color.Red("err=%v", err)
		return nil, err
	}

	return &account.Empty{A: 1}, nil
}
